use axum::Json;
use serde_json::{Value, from_str};
use reqwest::{self, Response, Error};
use crate::code;

pub async fn ajax(res: Result<Response, Error>)  -> Result<Value, Json<Value>> {
    match res {
        Ok(f) => {
            match f.text().await {
                Ok( r ) => {
                    match from_str::<Value>(&r) {
                        Ok(t) => Ok( t ),
                        Err(e) => Err(code::sys_(e.to_string()))
                    }
                },
                Err(e) => Err(code::sys_(e.to_string()))
            }
        },
        Err(e) => Err(code::sys_(e.to_string()))
    }
}
pub async fn get(url:&str)  -> Result<Value, Json<Value>> {
    ajax(reqwest::get(url).await).await
}
pub async fn pull(url:&str, param:Value)  -> Result<Value, Json<Value>> {
    let client = reqwest::Client::new();
    ajax(client.get(url).form(&param).send().await).await
}
pub async fn post(url:&str, param:Value)  -> Result<Value, Json<Value>> {
    let client = reqwest::Client::new();
    ajax(client.post(url).json(&param).send().await).await      // json 需要开启 json 特性
}